package com.zzy.jkb.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzy.jkb.api.CommonResult;
import com.zzy.jkb.api.ResultCode;
import com.zzy.jkb.constant.JkbConstant;
import com.zzy.jkb.entity.User;
import com.zzy.jkb.entity.VaccineHistory;
import com.zzy.jkb.service.IUserService;
import com.zzy.jkb.service.IVaccineHistoryService;
import com.zzy.jkb.service.impl.VaccineHistoryServiceImpl;
import com.zzy.jkb.util.PoiExcel;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 疫苗信息 前端控制器
 * </p>
 *
 * @author zzy
 * @since 2023-02-03
 */
@Controller
@RequestMapping("/jkb/vaccineHistory")
public class VaccineHistoryController {


    @Autowired
    IVaccineHistoryService iVaccineHistoryService;

    @Autowired
    IUserService iUserService;


    @RequestMapping(path = "/list", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("查询疫苗记录")
    public CommonResult<List<VaccineHistory>> list(@RequestParam String userId) {

        List<VaccineHistory> list = iVaccineHistoryService.list(Wrappers.lambdaQuery(VaccineHistory.class).eq(VaccineHistory::getUserId, userId).orderByDesc(VaccineHistory::getCreateTime));

        return CommonResult.success(list);
    }


    @Transactional
    @RequestMapping(path = "/save", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("接种新冠疫苗")
    public CommonResult save(@RequestParam String userId) {
        User user = iUserService.getById(userId);
        LambdaUpdateWrapper<User> userWrapper = Wrappers.lambdaUpdate(User.class).eq(User::getUuid, userId);
        VaccineHistory vaccineHistory =new VaccineHistory();
        VaccineHistory vaccine = iVaccineHistoryService.getOne(Wrappers.lambdaQuery(VaccineHistory.class).eq(VaccineHistory::getUserId, userId).orderByDesc(VaccineHistory::getCreateTime).last("limit 1"));
        if(vaccine!=null&&vaccine.getNeedlesNum().equalsIgnoreCase("第三针")){
            return CommonResult.validateFailed("已完成加强针，不需要接种疫苗");
        }
        if (vaccine!=null) {
            if(LocalDate.now().toEpochDay()-vaccine.getCreateTime().toLocalDate().toEpochDay()<28){
                return CommonResult.validateFailed("与上一针时间间隔未满四周");
            }

            //当前针数+1
            vaccineHistory.setNeedlesNum(JkbConstant.NeedlesNum.getMessage(JkbConstant.NeedlesNum.getValueCode(vaccine.getNeedlesNum())+1));
            //设置用户疫苗状态
            if(vaccine.getNeedlesNum().equalsIgnoreCase("第一针")){
                userWrapper.set(User::getVaccinumStatus,"已完成基础免疫");
            }
            if(vaccine.getNeedlesNum().equalsIgnoreCase("第二针")){
                userWrapper.set(User::getVaccinumStatus,"已完成加强免疫");
            }

        } else {
            //TODO 目前无法判断是否有基础疾病
            //判断是否满三周岁
            if(user!=null&&user.getBirthday()!=null){
                if (LocalDate.now().getYear() - user.getBirthday().getYear() < 3) {
                    return CommonResult.validateFailed("未满三周岁");
                }
            }
            //默认第一针
            vaccineHistory.setNeedlesNum(JkbConstant.NeedlesNum.ONE.getMsg());
            //设置用户疫苗状态
            userWrapper.set(User::getVaccinumStatus,"已完成基础免疫");
        }
        //接种时间
        vaccineHistory.setCreateTime(LocalDateTime.now());
        //先默认类型
        vaccineHistory.setType("Vero细胞");
        //先默认厂商
        vaccineHistory.setManufacturer("北京生物");
        iUserService.update(userWrapper);
        vaccineHistory.setUserId(userId);
        boolean save = iVaccineHistoryService.save(vaccineHistory);
        return CommonResult.autoCheck(save);
    }


    @RequestMapping(path = "/download", method = RequestMethod.POST)
    @ApiOperation("导出")
    public void download(HttpServletResponse response) throws Exception {
        PoiExcel.excelport(response);
    }
}
